import { useEffect, useState } from 'react';
import { useParams, useNavigate } from 'react-router-dom';
import {
  Card,
  Spin,
  Typography,
  Space,
  Button,
  Empty,
  message,
  Row,
  Col,
  Statistic,
  Table,
  Tag,
  Descriptions,
  Dropdown,
  type MenuProps,
} from 'antd';
import { ArrowLeftOutlined, DownloadOutlined, FilePdfOutlined, FileExcelOutlined } from '@ant-design/icons';
import ReactECharts from 'echarts-for-react';
import { getAssessmentReport, exportReportToPDF, exportReportToExcel, type AssessmentReport } from '@/api';
import type { EChartsOption } from 'echarts';

const { Title, Text, Paragraph } = Typography;

const Report = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(true);
  const [reportData, setReportData] = useState<AssessmentReport | null>(null);

  useEffect(() => {
    if (id) {
      loadReport();
    }
  }, [id]);

  const loadReport = async () => {
    if (!id) return;

    try {
      setLoading(true);
      const response = await getAssessmentReport(id);
      setReportData(response.data.data);
    } catch (error) {
      console.error('加载报告失败:', error);
      message.error('加载报告失败');
    } finally {
      setLoading(false);
    }
  };

  const handleExportPDF = async () => {
    if (!id) return;

    try {
      message.loading({ content: '正在生成PDF...', key: 'export' });
      await exportReportToPDF(id);
      message.success({ content: '导出PDF成功', key: 'export' });
    } catch (error) {
      console.error('导出PDF失败:', error);
      message.error({ content: '导出PDF失败', key: 'export' });
    }
  };

  const handleExportExcel = async () => {
    if (!id) return;

    try {
      message.loading({ content: '正在生成Excel...', key: 'export' });
      await exportReportToExcel(id);
      message.success({ content: '导出Excel成功', key: 'export' });
    } catch (error) {
      console.error('导出Excel失败:', error);
      message.error({ content: '导出Excel失败', key: 'export' });
    }
  };

  const exportMenuItems: MenuProps['items'] = [
    {
      key: 'pdf',
      label: '导出为PDF',
      icon: <FilePdfOutlined />,
      onClick: handleExportPDF,
    },
    {
      key: 'excel',
      label: '导出为Excel',
      icon: <FileExcelOutlined />,
      onClick: handleExportExcel,
    },
  ];

  if (loading) {
    return (
      <div style={{ textAlign: 'center', padding: '100px 0' }}>
        <Spin size="large" tip="加载中..." />
      </div>
    );
  }

  if (!reportData) {
    return <Empty description="报告不存在" />;
  }

  const { assessment, record, statistics, charts_data } = reportData;

  // 雷达图配置
  const radarOption: EChartsOption = {
    title: {
      text: '质量评估雷达图',
    },
    tooltip: {},
    radar: {
      indicator: charts_data.radar_chart.dimensions.map((name) => ({
        name,
        max: charts_data.radar_chart.max_score,
      })),
    },
    series: [
      {
        name: '评估得分',
        type: 'radar',
        data: [
          {
            value: charts_data.radar_chart.scores,
            name: '各维度评分',
            areaStyle: {
              color: 'rgba(24, 144, 255, 0.3)',
            },
          },
        ],
      },
    ],
  };

  // 柱状图配置
  const barOption: EChartsOption = {
    title: {
      text: '各维度评分对比',
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
    },
    xAxis: {
      type: 'category',
      data: charts_data.bar_chart.categories,
    },
    yAxis: {
      type: 'value',
      max: 100,
    },
    series: [
      {
        name: '得分',
        type: 'bar',
        data: charts_data.bar_chart.values.map((value, index) => ({
          value,
          itemStyle: {
            color: getBarColor(value),
          },
        })),
        label: {
          show: true,
          position: 'top',
        },
      },
    ],
  };

  // 仪表盘配置
  const gaugeOption: EChartsOption = {
    title: {
      text: '综合评分',
    },
    series: [
      {
        type: 'gauge',
        startAngle: 180,
        endAngle: 0,
        min: 0,
        max: 100,
        splitNumber: 10,
        itemStyle: {
          color: getScoreColor(charts_data.score_gauge.overall_score),
        },
        progress: {
          show: true,
          width: 18,
        },
        pointer: {
          show: false,
        },
        axisLine: {
          lineStyle: {
            width: 18,
          },
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          show: false,
        },
        axisLabel: {
          distance: 25,
          fontSize: 10,
        },
        detail: {
          fontSize: 40,
          offsetCenter: [0, '70%'],
          valueAnimation: true,
          formatter: '{value}分',
          color: 'inherit',
        },
        data: [
          {
            value: charts_data.score_gauge.overall_score,
            name: charts_data.score_gauge.grade,
          },
        ],
      },
    ],
  };

  // 问题类型饼图
  const issueTypePieOption: EChartsOption = {
    title: {
      text: '问题类型分布',
    },
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: 'right',
    },
    series: [
      {
        name: '问题数量',
        type: 'pie',
        radius: '50%',
        data: charts_data.issues_by_type.labels.map((label, index) => ({
          value: charts_data.issues_by_type.values[index],
          name: getIssueTypeName(label),
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  };

  // 问题严重程度饼图
  const issueSeverityPieOption: EChartsOption = {
    title: {
      text: '问题严重程度分布',
    },
    tooltip: {
      trigger: 'item',
    },
    legend: {
      orient: 'vertical',
      left: 'right',
    },
    series: [
      {
        name: '问题数量',
        type: 'pie',
        radius: '50%',
        data: charts_data.issues_by_severity.labels.map((label, index) => ({
          value: charts_data.issues_by_severity.values[index],
          name: label,
        })),
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)',
          },
        },
      },
    ],
  };

  // 问题列表列配置
  const issueColumns = [
    {
      title: '问题类型',
      dataIndex: 'issue_type',
      key: 'issue_type',
      render: (type: string) => (
        <Tag color={getIssueTypeColor(type)}>{getIssueTypeName(type)}</Tag>
      ),
    },
    {
      title: '严重程度',
      dataIndex: 'severity',
      key: 'severity',
      render: (severity: string) => (
        <Tag color={getSeverityColor(severity)}>{getSeverityName(severity)}</Tag>
      ),
    },
    {
      title: '字段名称',
      dataIndex: 'field_name',
      key: 'field_name',
    },
    {
      title: '问题描述',
      dataIndex: 'issue_description',
      key: 'issue_description',
      ellipsis: true,
    },
    {
      title: '扣分',
      dataIndex: 'score_deduction',
      key: 'score_deduction',
      render: (score: number) => <Text type="danger">-{score}</Text>,
    },
  ];

  return (
    <div>
      <Space style={{ marginBottom: 16 }}>
        <Button icon={<ArrowLeftOutlined />} onClick={() => navigate(-1)}>
          返回
        </Button>
        <Dropdown menu={{ items: exportMenuItems }} placement="bottomLeft">
          <Button type="primary" icon={<DownloadOutlined />}>
            导出报告
          </Button>
        </Dropdown>
      </Space>

      <Title level={2}>病历质量评估报告</Title>

      {/* 患者基本信息 */}
      <Card title="患者基本信息" style={{ marginTop: 16 }}>
        <Descriptions column={3} bordered>
          <Descriptions.Item label="姓名">{record.patient_name}</Descriptions.Item>
          <Descriptions.Item label="性别">{record.patient_gender || '-'}</Descriptions.Item>
          <Descriptions.Item label="年龄">
            {record.patient_age !== null ? `${record.patient_age}岁` : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="科室">{record.department || '-'}</Descriptions.Item>
          <Descriptions.Item label="就诊日期">
            {record.visit_date ? new Date(record.visit_date).toLocaleString('zh-CN') : '-'}
          </Descriptions.Item>
          <Descriptions.Item label="医生">{record.doctor_name || '-'}</Descriptions.Item>
          <Descriptions.Item label="诊断" span={3}>
            {record.diagnosis && record.diagnosis.length > 0
              ? record.diagnosis.join('; ')
              : '-'}
          </Descriptions.Item>
        </Descriptions>
      </Card>

      {/* 评估概况 */}
      <Card title="评估概况" style={{ marginTop: 16 }}>
        <Row gutter={16}>
          <Col span={6}>
            <Statistic
              title="总问题数"
              value={statistics.total_issues}
              suffix="个"
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="严重问题"
              value={statistics.critical_issues}
              valueStyle={{ color: '#cf1322' }}
              suffix="个"
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="主要问题"
              value={statistics.major_issues}
              valueStyle={{ color: '#fa8c16' }}
              suffix="个"
            />
          </Col>
          <Col span={6}>
            <Statistic
              title="次要问题"
              value={statistics.minor_issues}
              valueStyle={{ color: '#faad14' }}
              suffix="个"
            />
          </Col>
        </Row>
      </Card>

      {/* 图表展示 */}
      <Row gutter={16} style={{ marginTop: 16 }}>
        <Col span={12}>
          <Card>
            <ReactECharts option={gaugeOption} style={{ height: '400px' }} />
          </Card>
        </Col>
        <Col span={12}>
          <Card>
            <ReactECharts option={radarOption} style={{ height: '400px' }} />
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginTop: 16 }}>
        <Col span={24}>
          <Card>
            <ReactECharts option={barOption} style={{ height: '400px' }} />
          </Card>
        </Col>
      </Row>

      <Row gutter={16} style={{ marginTop: 16 }}>
        <Col span={12}>
          <Card>
            <ReactECharts option={issueTypePieOption} style={{ height: '400px' }} />
          </Card>
        </Col>
        <Col span={12}>
          <Card>
            <ReactECharts option={issueSeverityPieOption} style={{ height: '400px' }} />
          </Card>
        </Col>
      </Row>

      {/* 评估总结 */}
      {assessment.summary && (
        <Card title="评估总结" style={{ marginTop: 16 }}>
          <Paragraph>{assessment.summary}</Paragraph>
        </Card>
      )}

      {/* 改进建议 */}
      {assessment.suggestions && assessment.suggestions.length > 0 && (
        <Card title="改进建议" style={{ marginTop: 16 }}>
          <ul>
            {assessment.suggestions.map((suggestion, index) => (
              <li key={index}>
                <Text>{suggestion}</Text>
              </li>
            ))}
          </ul>
        </Card>
      )}

      {/* 问题详情 */}
      {assessment.issues && assessment.issues.length > 0 && (
        <Card title="问题详情" style={{ marginTop: 16 }}>
          <Table
            columns={issueColumns}
            dataSource={assessment.issues}
            rowKey="id"
            pagination={false}
          />
        </Card>
      )}
    </div>
  );
};

// 辅助函数
const getScoreColor = (score: number): string => {
  if (score >= 90) return '#52c41a';
  if (score >= 80) return '#1890ff';
  if (score >= 70) return '#faad14';
  if (score >= 60) return '#fa8c16';
  return '#f5222d';
};

const getBarColor = (value: number): string => {
  if (value >= 90) return '#52c41a';
  if (value >= 80) return '#1890ff';
  if (value >= 70) return '#faad14';
  return '#f5222d';
};

const getIssueTypeName = (type: string): string => {
  const typeMap: Record<string, string> = {
    completeness: '完整性',
    standardization: '规范性',
    consistency: '一致性',
    accuracy: '准确性',
  };
  return typeMap[type] || type;
};

const getIssueTypeColor = (type: string): string => {
  const colorMap: Record<string, string> = {
    completeness: 'blue',
    standardization: 'green',
    consistency: 'orange',
    accuracy: 'red',
  };
  return colorMap[type] || 'default';
};

const getSeverityName = (severity: string): string => {
  const nameMap: Record<string, string> = {
    critical: '严重',
    major: '主要',
    minor: '次要',
    info: '提示',
  };
  return nameMap[severity] || severity;
};

const getSeverityColor = (severity: string): string => {
  const colorMap: Record<string, string> = {
    critical: 'error',
    major: 'warning',
    minor: 'processing',
    info: 'success',
  };
  return colorMap[severity] || 'default';
};

export default Report;
